package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import decoder.ChineseDecoder;

import model.Member;
import factory.DaoFactory;

/**
 * Servlet implementation class LogOffServlet
 */
@WebServlet("/LogOffServlet")
public class LogOffServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogOffServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		Member member = DaoFactory.getMemberDao().find(name);
		request.setAttribute("member", member);
		String address ="/jsp/LogOff.jsp?name=" + name;
		RequestDispatcher dispatcher =request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = request.getParameter("name");
		
		boolean success = DaoFactory.getMemberDao().removeByName(name);
		
		if (success) {
			success = DaoFactory.getRecordDao().removeByCustomer(name);
			if (success) {
				response.sendRedirect(request.getContextPath() + "/LogInServlet");
			} else {
				response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=LogOffError&name=" + name);
			}
		} else {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=LogOffError&name=" + name);
		}
		
	}

}
